package com.wsj.filter;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class DealerCheckFilter implements Filter {

    protected FilterConfig filterConfig = null;
    protected String loginPath = null;

    public void destroy() {
        this.loginPath  = null;
        this.filterConfig = null;

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException 
    {

    	HttpServletRequest httpReq =(HttpServletRequest)request;
    	HttpServletResponse httpResp = (HttpServletResponse)response;
    	
    	if(!isAuthenticated(httpReq)){ 		
    		ServletContext context = filterConfig.getServletContext(  );
            RequestDispatcher rd = 
                context.getRequestDispatcher(loginPath);
            if (rd == null) {
                httpResp.sendError(
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 
                    "Login page doesn't exist");
            }
            rd.forward(request, response);
            return ;
    	}
        chain.doFilter(request, response);
 
    }
    
    /**
     * Returns true if the session contains the authentication token.
     */
    private boolean isAuthenticated(HttpServletRequest request) {
        boolean isAuthenticated = false;
        HttpSession session = request.getSession(  );
        if (session.getAttribute("dealer") != null) {
            isAuthenticated = true;
        }
        return isAuthenticated;
    }


    public void init(FilterConfig filterConfig) throws ServletException {

	    this.filterConfig = filterConfig;
        this.loginPath  = filterConfig.getInitParameter("loginPath");
        if(loginPath==null){
                throw new ServletException("loginPage init param missing");
        }
    }

}
